package com.szgd.controller.schedule;

import com.szgd.controller.BaseController;
import com.szgd.service.personnel.AttachService;
import com.szgd.service.schedule.AccessorStructureScheduleService;
import com.szgd.util.PropertiesUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping(value = "/accessorStructureSchedule")
public class AccessorStructureScheduleController extends BaseController {
    private static Logger logger = Logger.getLogger(AccessorStructureScheduleController.class);

    @Autowired
    AttachService attachService;
    @Autowired
    AccessorStructureScheduleService accessorStructureScheduleService;

    @RequestMapping(value = "toAccessor", method = RequestMethod.GET)
    public ModelAndView toAccessor(HttpServletRequest request, HttpSession httpSession) {
        ModelAndView mv = this.getModelAndView(request,httpSession,"/schedule/accessorSchedule/accessor");
        List<Map<String,Object>> dateList = accessorStructureScheduleService.getTime(null);
        mv.addObject("dateList", dateList);
        return mv;
    }


    @RequestMapping(value = "/uploadAccessorStructureSchedule", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> uploadAccessorStructureSchedule(@RequestParam("file") MultipartFile[] updateFiles, HttpSession httpSession) {
        try {
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            List<String> uploadFileNameList = new ArrayList<String>();
            InputStream is = updateFiles[0].getInputStream();
            String fileName = updateFiles[0].getOriginalFilename();
            int beginindex = fileName.indexOf("（");
            if (beginindex == -1)
                beginindex = fileName.indexOf("(");
            int endindex = fileName.indexOf("）");
            if (endindex == -1)
                endindex = fileName.indexOf(")");
            String dateStr  = "";
            if (beginindex > 0 && endindex > beginindex)
            {
                dateStr  = fileName.substring(beginindex+1,endindex).replace(".","-");
                if (dateStr.length() != 10)
                    return getErrorMap("文件名格式不对，没有含有日期或包含的日期格式不对，正确格式：XXX（YYYY.MM.DD）");
            }else
            {
                return getErrorMap("文件名格式不对，没有含有日期或包含的日期格式不对，正确格式：XXX（YYYY.MM.DD）");
            }
            boolean b = accessorStructureScheduleService.importAccessorStructureSchedule(updateFiles,this.getLoginId(httpSession));
            if (b)
                return getSuccMap("导入成功");
            else
                return getErrorMap("导入失败,请检查格式是否正确！");
        } catch (Exception e) {
            e.printStackTrace();
            return getErrorMap("文件上传失败！-------"+e.getMessage());
        }
    }

    @RequestMapping(value = "/isHavaAccessorStructureSchedule", method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> isHavaAccessorStructureSchedule(HttpServletRequest request, HttpServletResponse response) {
            String statisticsTime = getParam(request, "statisticsTime");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Map<String, Object> paramMap = new HashMap<>();
            try {
                Date date = sdf.parse(statisticsTime);
                Calendar cal = Calendar.getInstance();
                cal.setTime(date);
                int weekNo = cal.get(Calendar.WEEK_OF_MONTH);
                int monthNo = cal.get(Calendar.MONTH) + 1;

                cal.set(cal.DAY_OF_WEEK, cal.MONDAY);
                String weekhand = sdf.format(cal.getTime());
                paramMap.put("startStatisticsTime", weekhand);
                cal.set(Calendar.DATE, cal.get(cal.DATE) + 6);
                String weeklast = sdf.format(cal.getTime());
                paramMap.put("endStatisticsTime", weeklast);

                List<Map<String, Object>> tempList = accessorStructureScheduleService.getAccessorStructureScheduleList(paramMap);
                if (tempList == null || tempList.size() == 0) {
                    return getErrorMap(monthNo+"月份第"+weekNo+"周没有进度数据");
                } else
                    return getSuccMap("有数据");

            } catch (Exception e) {
                e.printStackTrace();
                return getErrorMap("查询失败！-------" + e.getMessage());
            }
    }

    @RequestMapping(value = "/downloadAccessorStructureSchedule")
    public void downloadAccessorStructureSchedule(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        String fileUploadPath = PropertiesUtil.get("uploadPath");
        String statisticsTime = getParam(request, "statisticsTime");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Map<String, Object> paramMap = new HashMap<>();
        try {
            Date date = sdf.parse(statisticsTime);
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);

            cal.set(cal.DAY_OF_WEEK, cal.MONDAY);
            String weekhand = sdf.format(cal.getTime());
            paramMap.put("startStatisticsTime",weekhand);
            cal.set(Calendar.DATE, cal.get(cal.DATE) + 6);
            String weeklast = sdf.format(cal.getTime());
            paramMap.put("endStatisticsTime",weeklast);

            List<Map<String,Object>> tempList = accessorStructureScheduleService.getAccessorStructureScheduleList(paramMap);
            if (tempList != null && tempList.size() > 0)
            {
                String attachId = tempList.get(0).get("attachId")==null?null:tempList.get(0).get("attachId").toString();
                if (attachId != null)
                {
                    Map<String, Object> attachMap = attachService.getAttach(attachId);
                    String fullPath = fileUploadPath + File.separator + attachMap.get("path")+ File.separator +  attachMap.get("name");
                    try {
                        this.download(response, fullPath);
                    } catch (IOException e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                    }
                }

            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/getChart")
    @ResponseBody
    public Map<String,Object> getChart(@RequestBody HashMap<String, Object> paramMap, HttpServletRequest request, HttpServletResponse response) {
        return accessorStructureScheduleService.getChart(paramMap);
    }

    @RequestMapping(value = "/getChartBySite")
    @ResponseBody
    public Map<String,Object> getChartBySite(@RequestBody HashMap<String, Object> paramMap, HttpServletRequest request, HttpServletResponse response) {
        return accessorStructureScheduleService.getChartBySite(paramMap);
    }

    @RequestMapping(value = "/getAccessorChartTable")
    @ResponseBody
    public Map<String,Object> getAccessorChartTable(@RequestBody HashMap<String, Object> paramMap, HttpServletRequest request, HttpServletResponse response) {
        return accessorStructureScheduleService.getChartTable(paramMap);
    }

    @RequestMapping(value = "/accessorCompleteRateAvg")
    @ResponseBody
    public Double accessorCompleteRateAvg(@RequestBody HashMap<String, Object> paramMap, HttpServletRequest request, HttpServletResponse response) {
        return accessorStructureScheduleService.accessorCompleteRateAvg(paramMap);
    }
}
